package org.linkerproject.server;

import java.io.IOException;
import java.net.InetSocketAddress;

import com.sun.net.httpserver.HttpServer;
import com.sun.net.httpserver.spi.HttpServerProvider;

public class Server extends Thread {

	private HttpServer httpServer;

	private String localPath;

	public Server(String path) {
		this.localPath = path + "/http";
	}

	@Override
	public void run() {
		port = 8707;
		host = "http://localhost";
		handler = new MyHttpHandler(localPath);

		try {
			HttpServerProvider httpServerProvider = HttpServerProvider
					.provider();
			InetSocketAddress addr = new InetSocketAddress(port);

			httpServer = httpServerProvider.createHttpServer(addr, 1);

			httpServer.createContext("/", handler);
			httpServer.setExecutor(null);
			httpServer.start();
			System.out.println("started");
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	public void save(String url, String html) {
		handler.save(url, html);
	}

	public void stopServer() {
		httpServer.stop(0);
	}

	public String getHost() {
		return host;
	}

	public int getPort() {
		return port;
	}

	private String host;

	private int port;

	private MyHttpHandler handler;

	public String getLocalUrl() {
		return this.getHost() + ":" + this.getPort() + "/";
	}
}
